package com.wgw.first.cart.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.wgw.first.R;
import com.wgw.first.cart.utils.CartStorage;
import com.wgw.first.dao.OrderBean;
import com.wgw.first.home.bean.GoodssBean;
import com.wgw.first.utils.Constants;

import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author Admin
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class OrderInfoActivity extends Activity implements View.OnClickListener{


    private EditText et_address;
    private EditText et_phone;
    private Button bt_commit;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_info);
        et_address = (EditText) findViewById(R.id.et_address);
        bt_commit = (Button)findViewById(R.id.bt_commit);
        et_phone = (EditText)findViewById(R.id.et_phone);
        bt_commit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //按钮点击后获取内容
        String address = et_address.getText().toString().trim();
        String phone = et_phone.getText().toString().trim();
        if((!address.isEmpty())&&(!phone.isEmpty())){

            System.out.println("点击了结算界面提交的按钮");

            //1，如果电话地址非空，则应该向服务器发送订单
            //取出intent里面中的list_order数组对象
            Intent intent = getIntent();
            List<OrderBean> list_order;
            list_order = (List<OrderBean>)intent.getSerializableExtra("orderlist");

            System.out.println(list_order.toString());
            for (int i = 0; i < list_order.size(); i++) {
                OrderBean orderBean = list_order.get(i);
                orderBean.setAddress(address);
                orderBean.setPhone(phone);
            }

            final String jsonorder = JSON.toJSONString(list_order);
            System.out.println(list_order.toString());
            System.out.println(jsonorder);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"),
                                "jsonorder="+jsonorder);
                        //                    RequestBody requestBody = new FormBody.Builder()
                        //                            .add("jsoncart",json_cart)
                        //                            .build();
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(Constants.BASE + Constants.UPORDERDATA)
                                .post(requestBody)
                                .build();
                        Response response = client.newCall(request).execute();
                        String responsedata = response.body().string();
                        System.out.println("OrderInfoActivity的responsedata:" + responsedata);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();


            //2,弹出toast
            Toast.makeText(this, "订单完成", Toast.LENGTH_SHORT).show();
            List<GoodssBean.Goods> list;
            list = CartStorage.getInstance(OrderInfoActivity.this).getDataFromLocal();

            //2，进行遍历，如果Isselected为true，则删除
            for (int i = 0; i < list.size(); i++) {
                GoodssBean.Goods goodsBean = list.get(i);
                if(goodsBean.isSelected()){
                    System.out.println("ISbn:"+goodsBean.getISBN());
                    CartStorage.getInstance(OrderInfoActivity.this).deleteData(goodsBean);
                    sendRequestWithOkHttp(OrderInfoActivity.this,goodsBean.getISBN());
                }
            }

            //3，退出当前activity
            finish();

        }else{
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();

        }

    }
    public void  sendRequestWithOkHttp(final Context context, final String delete_isbn) {
        if(Constants.ALEADYLOGIN==""){
            //如果用户未登录，则不同步数据库
            Toast.makeText(context, "未登录，将在本地数据库操作", Toast.LENGTH_SHORT).show();
        }else{
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String total = delete_isbn + "@" + Constants.ALEADYLOGIN;
                    System.out.println("delete_isbn:" + delete_isbn);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"),
                            "total="+total);
                    //                    RequestBody requestBody = new FormBody.Builder()
                    //                            .add("jsoncart",json_cart)
                    //                            .build();
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Constants.BASE + Constants.DELETESHOPPINGCART)
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responsedata = response.body().string();
                    System.out.println("delete:responsedata" + responsedata);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                }
            }).start();
        }
    }
}
